package com.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.system.pojo.Vendor;
import com.system.service.VendorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class VendorController {
    @Autowired
    private VendorService vendorService;

    @RequestMapping("selectAllVendorForPage")
    @ResponseBody
    public String selectAllVendorForPage(Vendor vendor, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "5") int limit) {
        List<Vendor> list = vendorService.selectVendor(vendor);
        List<Vendor> people = vendorService.selectVendorByPage(vendor, page, limit);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("count", list.size());
        jsonObject.put("data", people);
        jsonObject.put("msg", "查询成功");
        return jsonObject.toJSONString();
    }

    @RequestMapping("delVendor")
    @ResponseBody
    public String delVendor(Vendor vendor) {
        JSONObject jsonObject = new JSONObject();
        String id = vendor.getVendorCode().toString();
        try {
            vendorService.delVendor(id);
            jsonObject.put("code", 0);
            jsonObject.put("msg", "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("code", 1);
            jsonObject.put("msg", "删除失败");
        }
        return jsonObject.toJSONString();
    }

    @RequestMapping("insertVendor")
    @ResponseBody
    public String insertVendor(Vendor vendor, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        JSONObject jsonObject = new JSONObject();
        if (cookies != null) {
            System.out.println(cookies);
        }
        try {
            vendorService.insertVendor(vendor);
            jsonObject.put("code", 0);
            jsonObject.put("msg", "查询成功");
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("code", 1);
            jsonObject.put("msg", "删除失败");
        }
        return jsonObject.toJSONString();
    }

    @RequestMapping("updateVendor")
    @ResponseBody
    public String selectVendorForVendorCode(Vendor vendor) {
        JSONObject jsonObject = new JSONObject();
        try {
            vendorService.updateVendor(vendor);
            jsonObject.put("code", 0);
            jsonObject.put("msg", "修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("code", 1);
            jsonObject.put("msg", "修改失败");
        }
        return jsonObject.toJSONString();
    }

}
